package yl.hs.bmipfull.service.system.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.system.ICoreDataTagDao;
import yl.hs.bmipfull.daos.system.ISiteMessageMainDao;
import yl.hs.bmipfull.daos.system.ISiteMessageReceiptDao;
import yl.hs.bmipfull.daos.system.IUserInfoDao;
import yl.hs.bmipfull.pojo.system.RoleInfoEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageMainEntity;
import yl.hs.bmipfull.pojo.system.SiteMessageReceiptEntity;
import yl.hs.bmipfull.pojo.system.UserInfoEntity;
import yl.hs.bmipfull.service.system.ISiteMessageMainService;
import yl.hs.bmipfull.utils.HsApp;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.utils.datastate.MsgType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 作用:  站内信息服务层接口实现<br/>
 * 创建时间: 2021年05月12日 16时09分41秒 <br/>
 *
 * @author 张凯
 */
@Service
public class SiteMessageMainServiceImpl extends SystemBaseService implements ISiteMessageMainService {

    @Autowired
    ISiteMessageMainDao messageMainDao;
    @Autowired
    ISiteMessageReceiptDao receiptDao;
    @Autowired
    IUserInfoDao userDao;
    @Autowired
    ICoreDataTagDao coreDataTagDao;

    @Override
    public PageResult<SiteMessageMainEntity> queryList(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(SiteMessageMainEntity.class);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        var user= HsApp.getCurrent();
        pageQuery.getQuery().put("senderSN", user.getUserSN());
        PageResult<SiteMessageMainEntity> result = new PageResult(rowNum);
        result.setRecords(messageMainDao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        result.setData(messageMainDao.queryList(pageQuery.getQuery()));
        return result;
    }

    @Override
    public SiteMessageMainEntity findBySn(String sn) {
        return messageMainDao.findBySN(sn);
    }

    @Override
    @Transactional
    public Integer saveSiteMessageMain(Map<String, Object> model, String[] userSn, String[] receiptType) throws Exception {
        Integer result = 0;
        SiteMessageMainEntity entity = new SiteMessageMainEntity();
        //执行保存
        Tl.getChangeLog(entity, model);
        entity.setPYFieldValue();
        String mainSn = queryNewSN(SiteMessageMainEntity.class);
        entity.setSn(mainSn);
        result = messageMainDao.insertNew(entity);
        for (int i = 0; i < userSn.length; i++) {
            UserInfoEntity userInfo = userDao.findBySN(userSn[0]);
            SiteMessageReceiptEntity receiptEntity = new SiteMessageReceiptEntity();
            receiptEntity.setMsgSN(mainSn);
            receiptEntity.setReceiptType(Short.valueOf(receiptType[0]));
            receiptEntity.setReceiptTime(entity.getSendTime());
            receiptEntity.setReceipterSN(userInfo.getSn());
            receiptEntity.setReceipterName(userInfo.getAccount());
            result += receiptDao.insertNew(receiptEntity);
        }
        if (result > 0) {
            writeLog(ActionType.CREATE, entity.getSn(), "插入站内信息信息", Tl.toJson(entity), SiteMessageMainEntity.class);
        }
        return result;
    }

    @Override
    @Transactional
    public Integer delete(String[] sn) {
        Integer result = 0;
        for (String s : sn) {
            var bySn = findBySn(s);
            bySn.setState((short) -1);
            result = +messageMainDao.update(bySn);
        }

        return result;
    }

    @Override
    public Map<String, Object> getTypeCount(String userSN) {
        Map<String,Object> result=new HashMap<>();
        var list=messageMainDao.getListBySenderSN(userSN);
        var bulletin=0;
        var instant=0;
        for (var entity:list) {
            if (entity.getMsgType()==MsgType.Bulletin.code){
                bulletin+=1;
            }else if (entity.getMsgType()==MsgType.Instant.code){
                instant+=1;
            }
        }
        result.put("all",bulletin+instant);
        result.put("bulletin",bulletin);
        result.put("instant",instant);
        return result;
    }

    @Override
    public Integer updateState(String sn, short state) {
        var user = HsApp.getCurrent();
        var tags = coreDataTagDao.queryBySN(user.getUserSN().split(","));
        var roleCode = Tl.getDBMapCode(RoleInfoEntity.class);
        var roles = tags.stream().filter(p -> p.getTagType().equals(roleCode) && p.getMainSN().equals(user.getUserSN())).map(p -> p.getTagSN()).collect(Collectors.toList());
        String sql="(";
        sql=sql+"receipterSN like '%"+user.getUserSN()+"%'";

        if(roles.size()>0){
            for (var roleSn: roles) {
                sql=sql+"or receipterSN like '%"+roleSn+"%'";
            }
        }
        if(user.getDutySN()!=null && !user.getDutySN().equals("") && user.getDutySN().split(",").length>0){
            for (var dutySn: user.getDutySN().split(",")) {
                sql=sql+"or receipterSN like '%"+dutySn+"%'";
            }
        }
        if(user.getOrganizationCode()!=null&& !user.getOrganizationCode().equals("") && user.getOrganizationCode().split(",").length>0){
            for (var organizationCode: user.getOrganizationCode().split(",")) {
                sql=sql+"or receipterSN like '%"+organizationCode+"%'";
            }
        }
        sql=sql+")";
        if(sn!=null && sn !=""){
            sql = sql+" and msgSN = '"+sn+"'";
            var entity = receiptDao.queryByCondition(sql);
            entity.forEach(t->{
                t.setState(state);
                receiptDao.update(t);
            });
            return 1;
        }
        var entity = receiptDao.queryByCondition(sql);
        entity.forEach(t->{
            t.setState(state);
            receiptDao.update(t);
        });
        return 2;
    }

    @Override
    public Integer updateStateSite(String usersn, String sn, short state) {
        if(sn!=null && sn !=""){
            var entity = receiptDao.findByMsgSN(usersn,sn);
            entity.setState(state);
            return receiptDao.update(entity);
        }
        return 2;
    }

    @Override
    public Integer findList(List<String> listsn) {
        return messageMainDao.findBySnList(listsn);
    }
}